//package com.xry.test1.service.impl;
//
//import com.fasterxml.jackson.databind.JsonNode;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.xry.test1.model.GasData;
//import com.xry.test1.model.SoliData;
//import com.xry.test1.service.IHomeService;
//import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.messaging.simp.SimpMessagingTemplate;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Service;
//
//import java.time.LocalDateTime;
//
//@Service
//public class SoliServiceImpl implements IHomeService {
//    @Autowired
//    private SimpMessagingTemplate messagingTemplate; // WebSocket 消息推送
//
//    @Autowired
//    private MQTTSubscribe mqttSubscribe; // MQTT 订阅
//
//    //private Integer lastMessage = -1; // 记录上一次的消息，避免重复推送
//
//
//    /**
//     * 每秒查询一次 MQTT 数据并推送到前端
//     */
//    @Scheduled(fixedRate = 1000) // 每秒执行一次
//    public void checkAndPushMqttMessage() {
//        try {
//            String message = mqttSubscribe.waitForMessage(); // 等待消息
//            SoliData soliData = new SoliData();
//            ObjectMapper objectMapper = new ObjectMapper();
//            JsonNode jsonNode = objectMapper.readTree(message);
//            soliData.setMoisture(jsonNode.get("moisture").asInt());
//            soliData.setDate(LocalDateTime.now().toString());
//
//            messagingTemplate.convertAndSend("/topic/soliData",soliData);
//            System.out.println("✅  推送 WebSocket 数据：" + soliData);
//            //}
//        } catch (Exception e) {
//            System.out.println("❌ MQTT 获取数据失败soli：" + e.getMessage());
//        }
//    }
//}

package com.xry.test1.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xry.test1.dao.SoilRepository;
import com.xry.test1.dao.WaterRepository;
import com.xry.test1.model.SoilData;
import com.xry.test1.model.WaterData;
import com.xry.test1.service.IHomeService;
import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
import com.xry.test1.service.MQTTSubscriber.MqttMessageHandler;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import jakarta.annotation.PostConstruct;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static java.lang.Thread.sleep;

@Service
public class SoilServiceImpl implements IHomeService, MqttMessageHandler {
    //数据库
    @Autowired
    private SoilRepository soilRepository;

    @Autowired
    private WaterRepository waterRepository;


    @Autowired
    private SimpMessagingTemplate messagingTemplate; // WebSocket 消息推送

    @Autowired
    private MQTTSubscribe mqttSubscribe; // MQTT 订阅

    private static final String SOIL_TOPIC = "soil_moisture_1"; // 只订阅 soilMoisture 主题
    private static final String WATER_TOPIC = "water_pump_1"; // 只订阅 soilMoisture 主题
    private Integer lastMoisture = -1; // 记录上一次的土壤湿度，避免重复推送

    @PostConstruct
    public void init() {
        mqttSubscribe.subscribeToTopic(SOIL_TOPIC,this);
        //System.out.println("✅ SoilService 已订阅主题：" + SOIL_TOPIC);
    }

    public void handleIncomingMessage(String topic, MqttMessage message) {
        if (!SOIL_TOPIC.equals(topic)) {
            return; // 过滤掉非 soliMoisture 主题的消息
        }

        try {
            String payload = new String(message.getPayload());
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(payload);

            int moisture = jsonNode.get("moisture").asInt();
            int temp = jsonNode.get("temp").asInt();
            int hum = jsonNode.get("hum").asInt();

            // 只有当数据发生变化时才推送，避免重复推送相同数据
           // if (moisture != lastMoisture) {
                lastMoisture = moisture;

                SoilData soilData = new SoilData();
                soilData.setMoisture(moisture);
                soilData.setTemp(temp);
                soilData.setHum(hum);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                soilData.setDate(LocalDateTime.now().format(formatter));

                //mysql
                soilRepository.save(soilData);

                messagingTemplate.convertAndSend("/topic/soilData", soilData);
                System.out.println("  推送 WebSocket 数据：" + soilData);
           // }
        } catch (Exception e) {
            System.out.println("soli 解析 MQTT 消息失败：" + e.getMessage());
        }
    }

    public boolean water_pump(){
        WaterData waterData = new WaterData();
        waterData.setIsWatering("已浇水");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        waterData.setDate(LocalDateTime.now().format(formatter));

        //mysql
        waterRepository.save(waterData);

        mqttSubscribe.sendMQTTMessage(WATER_TOPIC, "3", 2);
        System.out.println("向水泵发送：3");
        try {
            Thread.sleep(3000); // 1000毫秒，也就是1秒。
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            return false;
        }
        mqttSubscribe.sendMQTTMessage(WATER_TOPIC, "0", 2);
        System.out.println("向水泵发送：0");
        return true;
    }
}

